window.addEvent('domready', function() {
	// CONFIG
	var texts = ["Add as much text as you want.","Remove text by clicking on that minus sign.","Click on text to edit it.", "Press Escape while editing to exit. Enter to save.", "Clicking anywhere on the document and pressing Esc will abort the changes."];
	// END OF CONFIG

	// Refreshes the Text Array
	function refresh() {
		// clean-up
		$$(".row").each( function(r) {
			r.removeEvents();
		});
	
		var out = "";
		
		out += "<table class=\"pills\">";
		
		texts.each(function(el) {
			out += "<tr><td class=\"row pill\">" + el + "</td><td class=\"removeButton\"></td></tr>";
		});
		
		out += "</table>";
		
		$('output').setHTML(out);
		
		// Assigns "remove item" action
		$$(".removeButton").each(function(r,i) {
			r.addEvent('click', function() {
				texts.splice(i,1);
				refresh();
			});
		});
		
		// assigb "edit item" action - click on the pills
		$$(".row").each(function(r,i) {
			r.addEvent('click', function() {
				var val = r.getText();
				
				// if val is empty, this means that the input field is already running. Exit
				if (val == "") return;
				
				r.setHTML("<input value=\"" + val +"\">");
				
				var inputfld = r.getElement("input");
				
				// add actions to this input field
				inputfld.addEvent('keyup', function(e) {
					var event = new Event(e);
					
					if (event.key == 'enter') {
						// save on enter
						r.setHTML(inputfld.getValue());
						inputfld.removeEvents();
					} else if (event.key == 'esc') {
						// leave on esc
						r.setHTML(val);
						inputfld.removeEvents();
					}
				});
			});
		});
	};
	
	// adds a new item
	$('add').addEvent('click', function() {
		texts.extend([$('new').getValue()]);
		$('new').empty();
		refresh();
	});
	
	// cancel any edits
	window.addEvent('keyup', function(e) {
		var event = new Event(e);
		
		if (event.key == 'esc') {
			refresh();
		}
	});
	
	// voila
	refresh();
});
